package com.hutou.chuangke.fragmentnet;

import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.hutou.chuangke.Bean.HouseBean;
import com.hutou.chuangke.Bean.TalkBean;
import com.hutou.chuangke.MainApplication;
import com.hutou.chuangke.R;
import com.hutou.chuangke.activity.AddTrackActivity;
import com.hutou.chuangke.activity.TrackDetailActivity;
import com.hutou.chuangke.adapter.ImageGridviewAdapter;
import com.hutou.chuangke.adapter.IndexSoundAdapter;
import com.hutou.chuangke.fragment.AttachFragment;
import com.hutou.chuangke.info.MusicInfo;
import com.hutou.chuangke.net.HttpUtil;
import com.hutou.chuangke.net.RequestThreadPool;
import com.hutou.chuangke.net.http.User;
import com.hutou.chuangke.uitl.BroadcastString;
import com.hutou.chuangke.widget.CircleImageView;
import com.hutou.chuangke.widget.DividerItemDecoration;
import com.hutou.chuangke.widget.MyGridview;
import com.hutou.chuangke.widget.SwipeRefreshLayout;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by o on 2017/3/18.
 * 动态列表
 */
public class TrackListFragment extends AttachFragment implements View.OnClickListener {
    private SwipeRefreshLayout swipeRefresh;
    private RecyclerView track_recyclerviewew;
    private ArrayList<TalkBean> mData = new ArrayList<>();
    LoadTrackListInfo loadTrackListInfo;
    Requestpraise requestpraise;//点赞请求
    Requestcancelpraise requestcancelpraise;

    private ImageView addtrack_iv;
    private TrackAdapter adapter;
    private int cruepage = 1;//页数
    private int pagesize = 10;//页长
    private static final String NET_PATH = "talkimgs/";
    private boolean isnomore = false;//没有更多了
    private boolean isPulling = false;
    private boolean isLoadmore = false;
    private boolean isFirst = true;

    @Override
    public View onCreateView(LayoutInflater inflater,  ViewGroup container,  Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_tracklist,null);
        return view;
    }

    @Override
    public void onViewCreated(View view,  Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init(view);
        initData();
        initReciver();
    }

    private void initReciver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(BroadcastString.UPDATE_TRACK_LIST);
        //注册广播

        getActivity().registerReceiver(mBroadcastReceiver, myIntentFilter);
    }


    private void initData() {
        loadData();
    }

    private void loadData() {
        loadTrackListInfo = new LoadTrackListInfo();
        loadTrackListInfo.execute();
    }

    private void init(View view) {
        track_recyclerviewew = (RecyclerView) view.findViewById(R.id.track_recyclerviewew);
        track_recyclerviewew.setLayoutManager(new LinearLayoutManager(getActivity()));
        track_recyclerviewew.addItemDecoration(new DividerItemDecoration(getContext(),DividerItemDecoration.VERTICAL_LIST));
        addtrack_iv = (ImageView) view.findViewById(R.id.addtrack_iv);
        adapter = new TrackAdapter();
        track_recyclerviewew.setAdapter(adapter);
        adapter.setonItemListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(getActivity(), TrackDetailActivity.class);
                intent.putExtra("track",mData.get(position));
                startActivity(intent);
//                Toast.makeText(getActivity(),"你点击了"+position,Toast.LENGTH_SHORT).show();
            }
        });
        swipeRefresh = (SwipeRefreshLayout) view.findViewById(R.id.swiperefresh);
        swipeRefresh.setHeaderView(crateHeadview());
        swipeRefresh.setFooterView(crateHeadview());
        swipeRefresh.setOnPullRefreshListener(new SwipeRefreshLayout.OnPullRefreshListener() {
            @Override
            public void onRefresh() {
                mData.clear();
                isPulling = true;
                isnomore = false;
                cruepage = 1;
                loadTrackListInfo.cancleTask();
                loadTrackListInfo = new LoadTrackListInfo();
                loadTrackListInfo.execute();
                swipeRefresh.setRefreshing(true);
            }

            @Override
            public void onPullDistance(int distance) {}

            @Override
            public void onPullEnable(boolean enable) {}
        });

        swipeRefresh.setOnPushLoadMoreListener(new SwipeRefreshLayout.OnPushLoadMoreListener() {
            @Override
            public void onLoadMore() {
                isLoadmore = true;
                loadTrackListInfo.cancleTask();
                loadTrackListInfo = new LoadTrackListInfo();
                loadTrackListInfo.execute();
                swipeRefresh.setLoadMore(true);
            }

            @Override
            public void onPushDistance(int distance) {

            }

            @Override
            public void onPushEnable(boolean enable) {

            }
        });
        addtrack_iv.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        if(v == addtrack_iv){
            Intent intent = new Intent(getActivity(), AddTrackActivity.class);
            startActivity(intent);
        }
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(action.equals(BroadcastString.UPDATE_TRACK_LIST)){
                isnomore = false;
                cruepage = 1;
                mData.clear();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        loadTrackListInfo = new LoadTrackListInfo();
                        loadTrackListInfo.execute();
                    }
                },10);

            }
        }

    };


    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(mBroadcastReceiver);
    }

    class LoadTrackListInfo extends AsyncTask<Void,Void,Boolean>{

        @Override
        protected Boolean doInBackground(Void... voids) {
            try{
                JsonObject list = HttpUtil.getResposeJsonObject(User.getTalkList(MainApplication.id,MainApplication.sid,cruepage,pagesize));
                JsonArray talkList = list.get("talkList").getAsJsonArray();//
                if(talkList.size() == 0){
                    isnomore = true;
                }
                String msg = list.get("msg").getAsString();
                for(JsonElement element : talkList){
                    mData.add(MainApplication.gsonInstance().fromJson(element,TalkBean.class));
                }
                return true;
            }catch(Exception e){
                e.printStackTrace();
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean comlete) {
            adapter.setData(mData);
            adapter.notifyDataSetChanged();
            if(isnomore){
                Toast.makeText(getActivity(),"没有更多了",Toast.LENGTH_SHORT).show();
            }else{
                cruepage++;
            }
            if(isPulling){
                swipeRefresh.setRefreshing(false);
                isPulling = false;
            }
            if(isLoadmore){
                swipeRefresh.setLoadMore(false);
                isLoadmore = false;
            }
        }

        public void cancleTask(){
            cancel(true);
            RequestThreadPool.finish();
        }
    }

    /**点赞请求*/
    class Requestpraise extends AsyncTask<String,Void,Boolean>{

        @Override
        protected Boolean doInBackground(String... params) {
            try{
                JsonObject list = HttpUtil.getResposeJsonObject(User.houseinto(MainApplication.id,MainApplication.sid,"2","5",params[0]));
                String flag = list.get("flag").getAsString();
                if(flag.equals("1")){
                    return true;
                }
                return false;
            }catch(Exception e){
                e.printStackTrace();
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean comlete) {
            if(comlete){
                Toast.makeText(getActivity(),"点赞成功",Toast.LENGTH_SHORT).show();
            }

        }

        public void cancleTask(){
            cancel(true);
            RequestThreadPool.finish();
        }
    }

    /**取消点赞请求*/
    class Requestcancelpraise extends AsyncTask<String,Void,Boolean>{

        @Override
        protected Boolean doInBackground(String... params) {
            try{
                JsonObject list = HttpUtil.getResposeJsonObject(User.houseDel(MainApplication.id,MainApplication.sid,params[0]));
                String flag = list.get("flag").getAsString();
                if(flag.equals("1")){
                    return true;
                }
                return false;
            }catch(Exception e){
                e.printStackTrace();
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean comlete) {
            if(comlete){
                Toast.makeText(getActivity(),"取消点赞",Toast.LENGTH_SHORT).show();
            }
        }
        public void cancleTask(){
            cancel(true);
            RequestThreadPool.finish();
        }
    }

    private View crateHeadview() {
        LayoutInflater inflater = LayoutInflater.from(getActivity());
        View view = inflater.inflate(R.layout.loading_circle,null);
        return view;
    }

    Handler handler = new Handler();

    public interface OnItemClickListener{
        void onItemClick(View view,int position);
    }

    class TrackAdapter extends RecyclerView.Adapter<TrackAdapter.ViewHolder>{
        private ArrayList<TalkBean> mData = new ArrayList<>();
        private OnItemClickListener mOnItemClickListener;

        public void setonItemListener(OnItemClickListener mOnItemClickListener){
            this.mOnItemClickListener = mOnItemClickListener;
        }
        @Override
        public TrackAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            TrackAdapter.ViewHolder holder = new TrackAdapter.ViewHolder(LayoutInflater.from(getActivity())
                    .inflate(R.layout.item_nearby,null));
            return holder;
        }

        @Override
        public void onBindViewHolder(final TrackAdapter.ViewHolder holder,final int position) {

            holder.nametv.setText(mData.get(position).getSinger());
            holder.datetv.setText(mData.get(position).getCrttm());
            holder.contexttv.setText(mData.get(position).getNote());
            ImageLoader.getInstance().displayImage(mData.get(position).getUimg(), holder.headiv);
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    int pos = holder.getLayoutPosition();
                    mOnItemClickListener.onItemClick(holder.itemView, pos);

                }
            });
            TalkBean bean = mData.get(position);
            if(!bean.getImgs().equals("")){
                holder.gridview.setVisibility(View.VISIBLE);
                List<String> list = new ArrayList<>();
                String[] sourceStrArray = bean.getImgs().split(",");
                for(String str: sourceStrArray){
                    list.add(str);
                }
                if(list.size()>0) {
                    ImageGridviewAdapter indexSoundAdapter = new ImageGridviewAdapter(getActivity(), list);
                    holder.gridview.setAdapter(indexSoundAdapter);
                }
            }else{
                holder.gridview.setVisibility(View.GONE);
            }
            holder.commenttv.setText(bean.getCollectnum()>999?999+"":bean.getCollectnum()+"");
            holder.isfollow_tv.setVisibility(View.GONE);
            if(bean.getIsfollow().equals("y")){
                holder.isfollow_tv.setText("已关注");
                holder.isfollow_tv.setCompoundDrawablesWithIntrinsicBounds(null,null,null,null);
            }else{
                holder.isfollow_tv.setText("关注");
                holder.isfollow_tv.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.add),null,null,null);
            }

//            holder.praiseiv.setChecked(bean.getIszan().equals("y")?true:false);
            if(bean.getIszan()!=null) {
                if (bean.getIszan().equals("y")) {
                    holder.praiseiv.setChecked(true);
                } else {
                    holder.praiseiv.setChecked(false);
                }
            }else {
                holder.praiseiv.setChecked(false);
            }
            holder.praiseiv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(holder.praiseiv.isChecked()){//点赞
                        requestpraise = new Requestpraise();
                        requestpraise.execute(mData.get(position).getId()+"");
                    }else{//取消点赞
                        requestcancelpraise = new Requestcancelpraise();
                        requestcancelpraise.execute(mData.get(position).getHouseid()+"");
                    }
                }
            });
        }

        public void setData(ArrayList<TalkBean> mData){
            this.mData = mData;
        }

        @Override
        public int getItemCount() {
            return mData.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder{
            TextView nametv,datetv,contexttv,addresstv,commenttv,praise_usernametv,isfollow_tv;
            ImageView headiv,commentiv,shareiv;
            LinearLayout praise_layout;
            FrameLayout add_view_layout;
            CheckBox praiseiv;
            MyGridview gridview;
            public ViewHolder(View view) {
                super(view);
                nametv = (TextView) view.findViewById(R.id.nametv);//昵称
                datetv = (TextView) view.findViewById(R.id.datetv);//时间
                contexttv = (TextView) view.findViewById(R.id.contexttv);//发布内容
                addresstv = (TextView) view.findViewById(R.id.addresstv);//地址
                commenttv = (TextView) view.findViewById(R.id.commenttv);//评论人数
                praise_usernametv = (TextView) view.findViewById(R.id.praise_usernametv);//点赞人名
                headiv = (CircleImageView) view.findViewById(R.id.headiv);//头像
                isfollow_tv = (TextView) view.findViewById(R.id.isfollow_tv);//关注按钮
                commentiv = (ImageView) view.findViewById(R.id.commentiv);//评论按钮
                praiseiv = (CheckBox) view.findViewById(R.id.praiseiv);//点赞按钮
                shareiv = (ImageView) view.findViewById(R.id.shareiv);//分享按钮
                praise_layout = (LinearLayout) view.findViewById(R.id.praise_layout);//点赞人名布局
                add_view_layout = (FrameLayout) view.findViewById(R.id.add_view_layout);
                gridview = (MyGridview) view.findViewById(R.id.gridview);
            }
        }
    }
}
